﻿using QDChat.Domain;
using QDChat.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QDChat.Data
{
    public class DbSession : IChatSession
    {
        private static string TableName = "chat_session";

        public int Insert(Session model)
        {
            using (var db = new QDMallDatabase())
            {
                db.Insert(model);
            }
            return model.Id;
        }

        public int AppendMsg(Session model)
        {
            using (var db = new QDMallDatabase())
            {
                return db.Execute($"update {TableName} set LastMsg=@0,sendTime={model.SendTime},FromMsgCount={model.FromMsgCount},ToMsgCount={model.ToMsgCount} where id={model.Id}", model.LastMsg);
            }
        }

        /// <summary>
        /// 清空未读消息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="countType">清空的类型(1 发送人, 2 接收人)</param>
        /// <returns></returns>
        public int ResetMsgCount(int id, int countType)
        {
            using (var db = new QDMallDatabase())
            {
                if (countType == 1)     //作为发送人，未读的消息
                    return db.Execute($"update {TableName} set fromMsgCount=0 where id={id}");
                if (countType == 2)     //作为接收人，未读的消息
                    return db.Execute($"update {TableName} set toMsgCount=0 where id={id}");
            }
            return 0;
        }

        public Session GetLast(int fromUid, int toUid)
        {
            using (var db = new QDMallDatabase())
            {
                return db.SingleOrDefault<Session>($"select top 1 * from {TableName} where (fromUid ={fromUid} and toUid={toUid}) or (fromUid ={toUid} and toUid={fromUid})");
            }
        }

        public List<SessionView> GetList(int toUid, int page, int pageSize)
        {
            using (var db = new QDMallDatabase())
            {
                return db.Fetch<SessionView>(page, pageSize, $"select * from {TableName} where toUid={toUid} or fromUid={toUid} order by sendTime desc");
            }
        }
    }
}